package demo;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Comparator;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.core.Path;
import com.jfinal.upload.UploadFile;

import demo.util.CharsetUtil;
import demo.util.EncodingDetect;

@Path("/upload")
public class UploadController extends Controller {
	public void index() {
    	render("upload.html");
    }
	
	public void upload() throws IOException{
		UploadFile uploadFile = getFile("file");
	    File file = uploadFile.getFile();
	    String renameFileName = file.getName().trim();
	    String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
	    
		File file2 = new File(path);
		String[] fileList = file2.list(); 
		String bookname=renameFileName.substring(0, renameFileName.lastIndexOf("."));
		boolean flagsame=false;
		for (String fileName : fileList) {
			if(fileName.equals(bookname)){
				flagsame=true;
				break;
			}
		}
		
		if(flagsame){
			renderJson((JSONObject) JSONObject.parse("{'res':'error','data':'has same name，canot updata'}"));
			return;
		}
		
		createdir(bookname,path);
		
		if (renameFileName.endsWith(".txt")) {
			String getEcording = EncodingDetect.getJavaEncode(file.getAbsolutePath());
			
			
			if(getEcording.equalsIgnoreCase("UTF-8")){
				String filePathnew = path +"\\"+bookname+"\\"+renameFileName;
            	file.renameTo(new File(filePathnew));
        	    renderJson((JSONObject) JSONObject.parse("{'res':'ok'}"));
			}else if(getEcording.equalsIgnoreCase("GB2312")||getEcording.equalsIgnoreCase("GBK")){
				String filePathnew = path +"\\"+bookname+"\\"+renameFileName;
                // 将 GBK 编码转成 UTF-8 编码
            	// 读取gbk编码格式的源文件
                FileInputStream fis = new FileInputStream(file.getPath());
                InputStreamReader isr = new InputStreamReader(fis, "gbk");
                BufferedReader br = new BufferedReader(isr);

                // 写入utf-8编码格式的目标文件
                FileOutputStream fos = new FileOutputStream(filePathnew);
                OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
                BufferedWriter bw = new BufferedWriter(osw);

                String line = null;
                // 逐行读取源文件内容，并写入目标文件
                while ((line = br.readLine()) != null) {
                    bw.write(line);
                    bw.newLine();
                }
                bw.flush();
                // 关闭IO流
                br.close();
                isr.close();
                fis.close();
                bw.close();
                osw.close();
                fos.close();
                file.delete();
                renderJson((JSONObject) JSONObject.parse("{'res':'ok'}"));
			}else{
				file.delete();
				renderJson((JSONObject) JSONObject.parse("{'res':'error','data':'only utf-8 or gbk can updata'}"));
				return;
			}
			
		}else{
	    	renderJson((JSONObject) JSONObject.parse("{'res':'error','data':'not txt file'}"));
	    	return;
	    }
	    
	    
	}
	
	public void list(){
		String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
		File file = new File(path);
		String[] fileList = file.list(); 
		JSONArray data=new JSONArray();
		for (String fileName : fileList) {
		    File subFile = new File(file.getPath() + "\\" + fileName);
		    if(subFile.isDirectory()){ 
		    	JSONObject jo=new JSONObject().parseObject("{'name':'"+subFile.getName()+"'}");
		        data.add(jo);
		    }
		}
		renderJson((JSONObject) JSONObject.parse("{'res':'ok','data':"+data.toJSONString()+"}"));
	}
	
	public void delete(){
		String jsonData = getRawData();
    	JSONObject jo = JSONObject.parseObject(jsonData);
    	String bookname=jo.getString("name").trim();
    	String path=getRequest().getServletContext().getRealPath("/")+"\\"+"book";
		File file = new File(path+"\\"+bookname);
		deleteFolder(file);
	    renderJson((JSONObject) JSONObject.parse("{'res':'ok'}"));
	}
	
	private void deleteFolder(File file) {
	    if (file.isDirectory()) {
	        File[] files = file.listFiles();
	        for (int i = 0; i < files.length; i++) {
	            deleteFolder(files[i]);
	        }
	    }
	    file.delete();
	}

	private String createdir(String bookname,String path) {
		
    	String filePath=path+"\\"+bookname;
	    
	    File saveDir = new File(filePath);
	    if (!saveDir.exists()) {
	        saveDir.mkdirs();
	    }
	    return filePath;
	}
	
}
